package org.chen.service;

import java.util.ServiceLoader;

/**
 * @Author czl
 * @Date 2024-04-30
 */
public class ShoppingCart {
    /**
     * 金额
     */
    private float amount;

    /**
     * 选择支付的服务
     */
    private PaymentService paymentService;


    public ShoppingCart() {
    }

    /**
     * 构造方法
     *
     * @param amount      金额
     * @param serviceName 服务名称
     */
    public ShoppingCart(float amount, String serviceName) {
        this.amount = amount;
        this.paymentService = choosePaymentService(serviceName);
    }

    /**
     * 选择支付服务
     *
     * @return 支付服务
     */
    public PaymentService choosePaymentService(String serviceName) {
        // 基于 SPI 机制，加载服务提供方 - 标准服务接口的实现
        ServiceLoader<PaymentService> loader =
                ServiceLoader.load(PaymentService.class);

        // 遍历所有的服务
        for (PaymentService service : loader) {
            if (serviceName != null && serviceName.equals(service.getServiceName())) {
                return service;
            }
        }
        throw new RuntimeException("请选择正确的支付方式");
    }

    /**
     * 结帐
     */
    public void checkout() {
        // 计算手续费
        float fee = this.paymentService.getHandlingFee(this.amount);
        // 计算总金额
        float totalAmount = fee + this.amount;

        System.out.println("金额:" + this.amount);
        System.out.println("手续费：" + fee);
        System.out.println("总金额：" + totalAmount);
        System.out.println("------------------------");
        this.paymentService.pay(totalAmount);
    }
}
